﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.CodeDom.Compiler;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Reflection;
using System.IO;
using ScriptCompiler2;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Net;
using LowLevelGraphics;
using LowLevelGraphics.Filter;

using Joshi.Utils.Imap;

using RemoteScriptingLibrary;
using Win32 = RemoteScriptingLibrary.Microsoft.Win32.Win32;

using WindowsRemoteScripting.Action;
using RemoteScriptingLibrary.ScriptCommands;

namespace WindowsRemoteScripting
{
    public partial class Form1 : Form
    {
        private WindowFinder windowFinder = new WindowFinder();
        protected MacroRecorder macroRecorder = new MacroRecorder();
        public static Form1 m_Form = null;
        public static IntPtr _hookID = IntPtr.Zero;

        private SortedDictionary<string, List<int>> aCommand = null;
        public Form1()
        {
            InitializeComponent();

            new Blub().Test();

            InitializeAutocompleteListBox();

            Script.m_Browser.Dock = DockStyle.Fill;
            Script.m_Browser.Parent = tabBrowser;

            Script.controlNeededForEditor = textBoxScript;

            Script.m_Browser.Navigated += new WebBrowserNavigatedEventHandler(m_Browser_Navigated);
            Script.m_Browser.Navigating += new WebBrowserNavigatingEventHandler(m_Browser_Navigating);

            nudTicksInterval.Value = macroRecorder.TickInterval;


            string sText = @"Do, 14.Mrz.2013 um 9:089:08
Message mit Stern versehen
von EuroClix an sie 
Jetzt Stromkosten senken und 50€ Wertkarte sichern!
Details ausblenden
Von
EuroClix
 
An
Holger Morlok
Für das problemlose Lesen unserer E-Mails fügen Sie EuroClix zur Liste mit sicheren Absendern zu. Mehr Infos.

	Ihr heutiger Kontostand ist: 382 Clix
			

				
	 	
Mit diesem Angebot sparen Sie:
6,50€ (500 Clix) 		 	
		Gültig bis einschließlich 28. März 2013. Benutzen Sie die E-Mail-Adresse: dr4g0n76@yahoo.com.	

	
		
		
		
		
	 Zusätzlich schenkt Discounter-Energie .de Ihnen eine 50 Wertkarte für Kioskpresse.de zum Kauf Ihrer Wunschzeitschriften! Dafür unbedingt Ihren Aktionscode DEO13KP3 angeben.	
		


		*Schauen Sie sich die Bedingungen auf der Webseite an.	

		

	 	Verdienen Sie ein Clix für das Klicken. Wechseln Sie jetzt zu Discounter-Energie.de und verdienen Sie 6,50€ (500 Clix).
	
				

		Wie funktioniert das?				Freunde werben				Abmelden				Disclaimer				Facebook Fan werden				Twitter Folger werden


";
            Match match = Regex.Match(sText, @"Ihr heutiger Kontostand ist: \d\d\d\d Clix");
            m_Form = this;

#if DEBUG
            AssemblyHelper.PrintMethodInfo(typeof(Script).GetMethods()); //output useable methods in console window (output)
#endif

            Script.m_OutputEventHandler += new Script.OutputEventHandler(Script_m_OutputEventHandler);

            GuiHelper.SetEventHandler(startToolStripMenuItem, new ExecuteScript());
            GuiHelper.SetEventHandler(chkbWindowFinder, windowFinder);
            GuiHelper.SetEventHandler(chkbMacroRecorder, macroRecorder);
            GuiHelper.SetEventHandler(cbExecuteScript, new ExecuteScript());
            GuiHelper.SetEventHandler(loadToolStripMenuItem1, new Load());
            GuiHelper.SetEventHandler(loadFromUrlToolStripMenuItem, new LoadFromURL());
            GuiHelper.SetEventHandler(saveToolStripMenuItem1, new Save());
            GuiHelper.SetEventHandler(redoToolStripMenuItem1, new Redo());
            GuiHelper.SetEventHandler(addClassCaptionToolStripMenuItem, new AddClassCaption());
            GuiHelper.SetEventHandler(addToolStripMenuItem, new WindowsRemoteScripting.Action.Add());
            GuiHelper.SetEventHandler(topmostToolStripMenuItem, new TopMost());
            GuiHelper.SetEventHandler(insertMousePositionToolStripMenuItem, new InsertMousePosition());
            GuiHelper.SetEventHandler(insertMouseMoveToolStripMenuItem, new InsertMouseMoveCommand());
            GuiHelper.SetEventHandler(insertClickCommandToolStripMenuItem, new InsertClickCommand());

            GuiHelper.SetEventHandler(quitToolStripMenuItem1, new ActionQuit());
            GuiHelper.SetEventHandler(helpToolStripMenuItem, new ActionShowHelp());
            GuiHelper.SetEventHandler(autosaveToolStripMenuItem, new ActionAutoSave());          
        }

        
        //public object AssignValue(object value, Type type)
        //{
        //    var i1 = new object();
        //    if (value == DBNull.Value)
        //    {
        //        value = DBNull.Value;
        //    }
        //    else
        //    {
        //        var conv = TypeDescriptor.GetConverter(type);
        //        i1 = conv.ConvertFrom(value);
        //    }
        //    return i1;
        //}

        private void InitializeAutocompleteListBox()
        {
            aCommand = AssemblyHelper.GetCommandsFromType(typeof(Script));
            cobText.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            cobText.AutoCompleteSource = AutoCompleteSource.CustomSource;

            AutoCompleteStringCollection aAutoCompleteFilterList = new AutoCompleteStringCollection();
            foreach (KeyValuePair<string, List<int>> keyValuePair in aCommand)
            {
                aAutoCompleteFilterList.Add(keyValuePair.Key);
            }
            cobText.AutoCompleteCustomSource = aAutoCompleteFilterList;
        }

        void Script_m_OutputEventHandler(object sender, Script.OutputEventArgs e)
        {
            rtbCustomMessageWindow.Invoke(new MethodInvoker(delegate() { rtbCustomMessageWindow.AppendText(e.ToString()); }));
        }

        void m_Browser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
        }

        void m_Browser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
        }

        private void textBox2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return || e.KeyCode == Keys.Enter)
            {
                string sText = cobText.Text;
                if (chkbAddToScript.Checked)
                {
                    textBoxScript.Text += sText + Environment.NewLine;
                }
                else
                {
                    textBoxScript.Text = sText;
                }
                if (!cobText.Items.Contains(sText))
                {
                    cobText.Items.Add(sText);
                }
                new ExecuteScript().Run(sender, e);
                if (chkbResetFocus.Checked)
                {
                    this.ActiveControl = cobText;
                    cobText.Focus();
                    Win32.SetActiveWindow(this.Handle);
                    Win32.SetForegroundWindow(this.Handle);
                    Win32.SetFocus(this.Handle);
                }
            }
        }
      
        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void addToolStripMenuItem1_Click(object sender, EventArgs e)
        {
        }

        private void stopToolStripMenuItem_Click(object sender, EventArgs e)
        {
            windowFinder.Stop();
        }

        private void redoToolStripMenuItem1_DropDownOpening(object sender, EventArgs e)
        {
            this.redoToolStripMenuItem1.Enabled = (ActionSingleton.Instance != null);
        }

        private void cobText_SelectedValueChanged(object sender, EventArgs e)
        {

        }

        private void cobText_TextChanged(object sender, EventArgs e)
        {
            string sText = string.Empty;
            string sParamText = this.cobText.Text;
            if (!aCommand.ContainsKey(sParamText)) return;

            List<int> aParameterCount = aCommand[sParamText];
            aParameterCount.Sort();
            foreach (int nCount in aParameterCount)
            {
                sText += nCount.ToString() + " ,";
            }
            sText = string.Format("{0} Params", sText.TrimEnd(','));

            lbMethodInfo.Text = sText;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            new MacroRecorder().Run(sender, e);
        }

        private void tbBrowse_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
            {
                Script.m_Browser.Navigate(tbBrowse.Text);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Script.m_Browser.Parent = this.tabBrowser;
            Script.m_Browser.Dock = DockStyle.Fill;

            SimpleTemplateMatching simpleTemplateMatching = new SimpleTemplateMatching();
            simpleTemplateMatching.MatchingMode = SIMPLE_TEMPLATE_MATCHING_MODE.MOST_EXACT_GRAY_MATCH;
            UnsafeBitmap template = @"c:\users\morlho\desktop\gefälltmir_neu.jpg";
            UnsafeBitmap bitmap = ImageTools.TakeScreenshot("", true);

            //Bitmap bitmap = ScreenShot.CaptureImage(false, new Size(1024,768),new Point(100,100),new Point(0,0), new Point(1024,768),new Rectangle(0,0,1024,768), @"c:\test\test.jpg",".jpg");
            string sFileName = string.Format(@"c:\users\morlho\desktop\screenshot{0}", DateTime.Now.ToString().Replace(":", ".") + ".jpg");
            bitmap.Save(sFileName);
            bitmap = UnsafeBitmap.FromFile(sFileName);
            simpleTemplateMatching.BitmapTemplate = template;
            simpleTemplateMatching.Execute(bitmap);

            template.Dispose();
            bitmap.Dispose();

            pictureBoxArea.BackgroundImage = template.InternalBitmap;
            pictureBoxScreen.BackgroundImage = bitmap.InternalBitmap;

            //Script.MouseMoveClick(@"c:\users\morlho\desktop\gefälltmir.jpg");

            if (simpleTemplateMatching.SADPositions.Count > 0)
            {
                this.Text = "OK";
                Script.MouseMove(simpleTemplateMatching.SADPositions[0].BestCol, simpleTemplateMatching.SADPositions[0].BestRow, 100, 10);
            }
            else
            {
                this.Text = "No position found to move to!";
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Script.WaitForActiveWindow("Unbenannt");
        }

        private void nudTicksInterval_ValueChanged(object sender, EventArgs e)
        {
            macroRecorder.TickInterval = (int)nudTicksInterval.Value;
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            FormCapture formCapture = new FormCapture();
            this.Hide();
            formCapture.InstanceRef = this;
            formCapture.Show();
        }

        private void saveToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            SaveFileDialog fd = new SaveFileDialog();
            if (fd.ShowDialog() != DialogResult.OK) return;
            pictureBoxArea.BackgroundImage.Save(fd.FileName);
        }

        private void button5_Click(object sender, EventArgs e)
        {
            Imap oImap = new Imap();

            String sHost = "imap.gmail.com";
            String sPort = "993";
            bool bSSL = true;
            String sUser = "xx";
            String sPwd = "xxxxxxx";

            oImap.Login(sHost, Convert.ToUInt16(sPort), sUser, sPwd, bSSL);
            oImap.SelectFolder("INBOX");

        }

        private void button6_Click(object sender, EventArgs e)
        {
            string sOutput = Script.LoadScriptToEditorFromURL("http://www.google.de");
            textBoxScript.Text = sOutput;
        }

        private void toClipboardToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Clipboard.SetData(DataFormats.Bitmap, pictureBoxArea.BackgroundImage);
        }

        private void fromClipboardToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Bitmap bitmap = (Bitmap)Clipboard.GetData(DataFormats.Bitmap);
            pictureBoxArea.BackgroundImage = bitmap;
        }
    }
}
